package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.privilege.client.ApplicationClient;
import com.leyou.privilege.dto.ApplicationDTO;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthService {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private UserClient userClient;

    private static final String USER_ROLE = "role_user";


    public void login(String username, String password, HttpServletResponse response) {


        try {
            //查询用户
            UserDTO user = userClient.queryUserByUsernameAndPassword(username,password);
            //生成userInfo，没写权限功能，暂时都用guest
            UserInfo userInfo = new UserInfo(user.getId(),user.getUsername(),USER_ROLE);
            //生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo,prop.getPrivateKey(),prop.getUser().getExpire());
            //写入cookie
            writeCookie(response, token);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }


    }

    private void writeCookie(HttpServletResponse response, String token) {
        CookieUtils.newCookieBuilder().response(response) //response,用于写cookie
                .httpOnly(true) //保证安全防止XSS攻击，不允许JS操作cookie
                .domain(prop.getUser().getCookieDomain()) //设置domain
                .name(prop.getUser().getCookieName()).value(token) //设置cookie名称和值
                .build();//写cookie
    }

    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {

        try {
            //读取Cookie
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            //获取token信息
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            //判断token是否在黑名单中
            Boolean isValid = redisTemplate.hasKey(payLoad.getId());
            if (isValid != null && isValid){
                //存在，说明是无效token，应该返回异常信息
                throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
            }
            //获取过期时间
            Date expiration = payLoad.getExpiration();
            //获取刷新时间
            DateTime refreshTime = new DateTime(expiration.getTime()).minusMillis(prop.getUser().getRefreshInterval());
            //判断是否已经过了刷新时间,如果过了就刷新cookie
            if (refreshTime.isBeforeNow()){
                //如果过了刷新时间，则生成新token
               String newtoken = JwtUtils.generateTokenExpireInMinutes(payLoad.getUserInfo(),prop.getPrivateKey(),
                        prop.getUser().getExpire());
                //写入cookie
                writeCookie(response, newtoken);
            }
            return payLoad.getUserInfo();
        } catch (Exception e) {
            log.error("用户信息认证失败",e);
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    public void logout(HttpServletRequest request, HttpServletResponse response) {

        //获取token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        if (StringUtils.isBlank(token)) {
            return;
        }
        //校验并解析token
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        //获取token的剩余有效期,单位是毫秒
        Date expiration = payload.getExpiration();
        long expire = expiration.getTime() - System.currentTimeMillis();
        //获取token中的id，写入redis中，标记无效，有效期为token的剩余有效期
        if (expire >= 5000) {
            redisTemplate.opsForValue().set(payload.getId(),"1",expire, TimeUnit.MILLISECONDS);
        }
        //删除cookie
        CookieUtils.deleteCookie(prop.getUser().getCookieName(),prop.getUser().getCookieDomain(),response);
    }

    
    @Autowired
    private ApplicationClient applicationClient;
    
    public String authentication(Long id, String secret) {

        try {
            //检验id和secret是否正确
            ApplicationDTO app = applicationClient.queryByAppIdAndSecret(id, secret);
            //生成JWT
            AppInfo appInfo = new AppInfo();
            appInfo.setId(app.getId());
            //appInfo.setServiceName(app.getServiceName());
            return JwtUtils.generateTokenExpireInSeconds(appInfo, prop.getPrivateKey(), prop.getApp().getExpire());
        } catch (Exception e) {
            log.error("【授权中心】验证服务id和secret出错", e);
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }


    }
}
